package com.atguitu.campus.renwendemo.service;

// UserDetailsServiceImpl.java

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    // 模拟数据库查询
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<com.atguitu.campus.renwendemo.entity.User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        com.atguitu.campus.renwendemo.entity.User user =  userService.getOne(queryWrapper);

        if (Objects.isNull(user)){
            throw new UsernameNotFoundException("User not found with username: " + username);
        }

        return User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .roles(user.getRoleKey())
                .build();
        // 实际应用中应该从数据库获取用户信息
        /*if ("admin".equals(username)) {
            return User.builder()
                    .username(user.getUsername())
                    .password("$2a$10$Ev5QSKJK98VohsDO9Tdwhe396R.3xAOHv7bEsCuE3eQzi5yoLka1.")
                    .roles("ADMIN")
                    .build();
        } else if ("user".equals(username)) {
            return User.builder()
                    .username("user")
                    .password("$2a$10$slYQmyNdGzTn7ZLBXBChFOC9f6kFjAqPhccnP6DxlWXx2lPk1C3G")
                    .roles("USER")
                    .build();
        } else {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }*/
    }
}